﻿import React from 'react';
import {Upload, Button, Icon, message, Modal} from 'antd';
import {mySpecsUpload} from '../../api';
import './MyUpload.scss';

class MyUpload extends React.Component {
  state = {
    visible: false,
    fileList: [],
    uploading: false,
    result: []
  };

  // model框开始
  showModal = () => {
    this.setState({
      visible: true
    });
  };

  handleOk = e => {
    console.log(e);
    this.setState({
      visible: false
    });
  };

  handleCancel = e => {
    console.log(e);
    this.setState({
      visible: false
    });
  };

  // model框结束
  handleUpload = () => {

    const {fileList} = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('files[]', file);
    });

    this.setState({
      uploading: true
    });

    mySpecsUpload(formData).then(res => {
      console.log(res);
      this.setState({
        fileList: [],
        uploading: false,
        result: res.data
      });
      message.success('上传成功...');
      this.showModal();
    }).catch(err => {
      console.log(err);
      this.setState({
        uploading: false
      });
      message.error('上传失败...');
    });

  };

  render() {
    const {uploading, fileList} = this.state;
    const props = {
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file]
        }));
        return false;
      },
      fileList
    };

    return (
      <div className={'MyUpload'}>
        <Upload {...props} >
          <Button icon={'upload'}>导 入</Button>
        </Upload>
        <Button
          type="primary"
          onClick={this.handleUpload}
          disabled={fileList.length === 0}
          loading={uploading}
        >
          {uploading ? '数据中上传...' : '开始上传'}
        </Button>
        <Modal
          width={1000}
          title="上传结果："
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <ul className={'myResult000111'}>
            {
              this.state.result.map((item, index) => (
                <li key={index}>{item.map((v, i) => <span key={index + i}>{v}</span>)}</li>
              ))
            }
          </ul>
        </Modal>
      </div>
    );
  }
}

export default MyUpload;
